<template>
  <div>
    <video id="myVideo" alt="my video" controls>
      <source src="./test.mp4" type="video/mp4" />
      Your browser does not support the video tag.
    </video>
    <img v-if="coverImage" :src="coverImage" alt="video cover image" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      coverImage: null,
    };
  },
  mounted() {
    const video = document.getElementById("myVideo");
    video.addEventListener(
      "loadedmetadata",
      () => {
        // 设置视频的暂停位置为0.01秒，以获取第一帧画面
        video.currentTime = 0.01;
      },
      false
    );
    video.addEventListener("seeked", () => {
      const canvas = document.createElement("canvas");
      const context = canvas.getContext("2d");

      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      // 将视频的第一帧绘制到canvas上
      context.drawImage(video, 0, 0, canvas.width, canvas.height);
      // 将canvas上的图片转换为base64格式的数据
      this.coverImage = canvas.toDataURL();
    });
  },
};
</script>

<style scoped lang="less"></style>
